import { relationalStore } from "@kit.ArkData";
import { Context } from "@kit.AbilityKit";

export let db:relationalStore.RdbStore | undefined = undefined

export function init(context:Context){
  relationalStore.getRdbStore(context, {
    name: 'test.db',
    securityLevel:relationalStore.SecurityLevel.S2
  },(err,store) => {
    if (err){
      console.log(`创建数据库失败，错误码：${err.code},错误信息：${err.message}`)
      return
    }
    db = store
    if (db.version == 0) { // 从版本0 升级到 版本2
      db.executeSql('create table user(id integer primary key autoincrement, username text not null, password text not null, address text not null);')
        .then(() => {
          console.log('创建成功')
          db!.version = 2
        })
        .catch((e:Error) => {
          console.log(`创建失败，错误信息：${e.message}}`)
        })
    }
    if (db.version == 1){// 从版本1 升级到 版本2
      db.executeSql('alter table user add column address text not null default "默认地址";')
        .then(() => {
          console.log('升级数据库成功')
          db!.version = 2
        })
        .catch((e:Error) => {
          console.log(`升级数据库失败，错误信息：${e.message}}`)
        })
    }
    console.log('初始化完成')
  })
}
